package com.mti.threadhandle;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mti.component.snowflake.KeyWorker;
import com.mti.constant.AlarmFilterEnum;
import com.mti.dao.model.KmJurisdictionEntity;
import com.mti.dao.model.KmPhYjEntity;
import com.mti.dao.model.KmZdryAssistEntity;
import com.mti.dao.model.LfZtryyjEntity;
import com.mti.service.*;
import com.mti.utils.AddressOrLngLatConvertUtil;
import com.mti.utils.ZdryYjUtilBean;
import com.mti.websocket.SocketType;
import com.mti.websocket.WebSocketUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;

/**
 * @Classname PhoneYjDataHandle
 * @Description TODO
 * @Date 2020/4/29 21:03
 * @Created by duchaof
 * @Version 1.0
 */
@Slf4j
@Data
@AllArgsConstructor
public class PhoneYjDataHandle implements Runnable {

    private KmPhYjService phYjService;

    private KmPhYjEntity kmPhYjEntity;

    private ILfZtryyjsjService iLfZtryyjsjService;

    private AddressOrLngLatConvertUtil addressOrLngLatConvertUtil;

    private WebSocketUtils webSocketUtils;

    private LfZdryBaseService lfZdryBaseService;

    private KmJurisdictionService kmJurisdictionService;

    private KmZdryAssistService kmZdryAssistService;

    private Lock lock;


    @Override
    public void run() {
        lock.lock();
        try {
            // 离开区域的入库：alarm_location ，但是不给ds推送
            // 根据身份证号 和 预警电话判断重点人员是否存在这个电话号码，没有就插入
            Map<String, String> zdry = lfZdryBaseService.findZdryBySfzhAndSjh(kmPhYjEntity.getIdCard(), kmPhYjEntity.getPhone());
            if (null == zdry) return;
            if (!zdry.containsKey("sjh")) {
                KmZdryAssistEntity kmZdryAssistEntity = new KmZdryAssistEntity();
                kmZdryAssistEntity.setId(String.valueOf(KeyWorker.nextId()));
                kmZdryAssistEntity.setInfoType(1);
                kmZdryAssistEntity.setInfoValue(kmPhYjEntity.getPhone());
                kmZdryAssistEntity.setZdryId(zdry.get("id"));
                kmZdryAssistEntity.setIndex(1);//此标识为临时测试使用，意义为新增的手机号区分，后续去掉
                kmZdryAssistService.save(kmZdryAssistEntity);

            }
            // 判断重复数据： 1小时之内重复：alarm_location，id_card，name，phone；alarm_time 根据这个时间进行判断
            List<KmPhYjEntity> data = phYjService.list(new QueryWrapper<KmPhYjEntity>().lambda()
                    .likeRight(KmPhYjEntity::getAlarmLocation, kmPhYjEntity.getAlarmLocation().split("-")[0])
                    .eq(KmPhYjEntity::getIdCard, kmPhYjEntity.getIdCard())
                    .eq(KmPhYjEntity::getName, kmPhYjEntity.getName())
                    .eq(KmPhYjEntity::getPhone, kmPhYjEntity.getPhone())
                    .orderByDesc(KmPhYjEntity::getAlarmTime));
            boolean insertFlag = true;
            if (data.size() > 0) {
                try {
                    KmPhYjEntity phyj = data.get(0);
                    Long hours = (kmPhYjEntity.getAlarmTime().getTime() - phyj.getAlarmTime().getTime()) / (1000 * 60 * 60);
                    if (hours < 1) insertFlag = false;
                } catch (Exception e) {
                    log.error("比较时间时发生错误：" + e.getMessage());
                    insertFlag = false;
                }
            }
            if (insertFlag) {
                // 接受到消息后先加入到手机预警信息表 t_km_ph_yj
                boolean flag = phYjService.save(kmPhYjEntity);
                if (flag) {
                    LfZtryyjEntity lfZtryyjEntity = kmPhYjEntity.convertZdryYj();
                    KmJurisdictionEntity kmJurisdictionEntity = null;
                    if (null != lfZtryyjEntity.getX() && !"".equals(lfZtryyjEntity.getX().trim()) || null != lfZtryyjEntity.getY() && !"".equals(lfZtryyjEntity.getY().trim())) {
                        String currentJur = addressOrLngLatConvertUtil.checkAddress(lfZtryyjEntity.getX(), lfZtryyjEntity.getY());
                        lfZtryyjEntity.setCurrentJur(currentJur);
                        kmJurisdictionEntity = kmJurisdictionService.queryYjdPcsByLngAndLat(lfZtryyjEntity.getX(), lfZtryyjEntity.getY());
                    } else {
                        lfZtryyjEntity.setX("102.719775");
                        lfZtryyjEntity.setY("24.839721");
                    }

                    if (null != kmJurisdictionEntity) {
                        lfZtryyjEntity.setYjdPcs(kmJurisdictionEntity.getMc());
                        lfZtryyjEntity.setYjdPcsCode(String.format("%.0f", Double.parseDouble(kmJurisdictionEntity.getDm())));
                        lfZtryyjEntity.setYjdSsfj(kmJurisdictionEntity.getSsfj());
                    }

                    //检测是否符合预警拦截


                    //插入预警表，方便后续的操作
                    boolean ylSign = iLfZtryyjsjService.save(lfZtryyjEntity);
                    ZdryYjUtilBean zdryYjUtilBean = lfZtryyjEntity.convertZdryYjUtilBean();

                    if (null != kmJurisdictionEntity) {
                        StringBuilder sb = new StringBuilder("重点人员【");
                        sb.append(lfZtryyjEntity.getRyxm()).append("】在").append(kmJurisdictionEntity.getMc())
                                .append("的管辖范围内发生了手机定位。");
                        zdryYjUtilBean.setYjMsg(sb.toString());
                    }

                    if (ylSign) {
                        //检测是否符合预警推送规则
                        boolean isAllowed = iLfZtryyjsjService.authEarlyWarning(lfZtryyjEntity, AlarmFilterEnum.PHONE_SWITCH.getName());
                        if (!isAllowed) {
                            return;
                        }

                        List<String> tokens = iLfZtryyjsjService.findWebsocketPsuhUserListByYjwybs(lfZtryyjEntity.getWybs());

                        if (null != tokens && tokens.size() > 0) {
                            webSocketUtils.sendWebsockMessageToUser(tokens, Arrays.asList("phyj", JSON.toJSONString(zdryYjUtilBean)), SocketType.ZDRRYJXX.getCode());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("插入时异常：======> {}", e.getMessage());
        } finally {
            lock.unlock();
        }
    }
}
